package org.kaer.election.fragment;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.irecyclerview.IRecyclerView;
import com.aspsine.irecyclerview.OnLoadMoreListener;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.kaer.election.R;
import org.kaer.election.adapter.PositionAdapter;
import org.kaer.election.adapter.SearchCandidateAdapter;
import org.kaer.election.bean.Candidate;
import org.kaer.election.bean.Positions;
import org.kaer.election.bean.SelectedElection;
import org.kaer.election.ite.OnRecycleItemClickListener;
import org.kaer.election.trade.ExampleClient;
import org.kaer.election.utils.CommonUtil;
import org.kaer.election.utils.GridItemDecoration;
import org.kaer.election.utils.JSONKeys;
import org.kaer.election.utils.LogUtils;
import org.kaer.election.widget.LoadMoreFooterView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;


/**
 * Created by lizj on 2016/7/15.
 */
public class ElectionFragment extends BaseFragment implements AdapterView.OnItemClickListener, View.OnClickListener, OnLoadMoreListener {
    private GridView positionGv;
    private IRecyclerView candidateGv;
    private BaseAdapter posAdapter/*, canAdapter*/;
    private SearchCandidateAdapter canAdapter;
    private TextView allowNumTv, selNumTv, leastNumTv;
    private LinearLayout descLL;
    private LinearLayout searchLL;
    private Button voteBtn, queryBtn;
    private EditText searchEt;
    private String cardId;//证件id
    private SelectedElection election;
    private List<Positions> posList;
    private List<Candidate> canList;
    private HashMap<Integer, Integer> referencePosMap;
    private HashMap<String, Integer> referenceCanMap;
    private int lastPosPosition; //上次选中的职位
    private AnimatorSet mSet;
    private Gson mGson;
    private LoadMoreFooterView loadMoreFooterView;
    private int totalCount, currentCount;  //该索引能返回的总数,该索引已返回的数量
    private final int QUERY_COUNT = 8; // 每次请求的数量
    private boolean hasMore, filterFlag;

    public static ElectionFragment newInstance(Bundle mBundle) {
        ElectionFragment fragment = new ElectionFragment();
        fragment.setArguments(mBundle);
        return fragment;
    }

    public void updateBundle(Bundle bundle) {
        mBundle = bundle;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_election;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return super.onCreateView(inflater, container, savedInstanceState);
    }


    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        mGson = new Gson();
        queryBtn = (Button) findView(R.id.election_btnQuery);
        queryBtn.setOnClickListener(this);
        positionGv = (GridView) view.findViewById(R.id.election_gvPosition);
        String data = mBundle.getString(JSONKeys.Voter.ElectionData);
        cardId = mBundle.getString(JSONKeys.Voter.CardId);
        election = new Gson().fromJson(data, SelectedElection.class);
        getHoldingActivity().initTitle(election.electionName);
        Positions[] posArr = election.positionList;
        posList = Arrays.asList(posArr);
        referencePosMap = new HashMap<Integer, Integer>();
        for (int i = 0; i < posArr.length; i++) {
            referencePosMap.put(posArr[i].positionId, i);
        }
        int numColumn = 3;
        if (posArr.length == 4 || posArr.length == 2 || posArr.length == 1)
            numColumn = 2;
        lastPosPosition = -1;
        positionGv.setNumColumns(numColumn);
        positionGv.setAdapter(posAdapter = new PositionAdapter(mContext, posList));
        positionGv.setOnItemClickListener(this);
//        candidateGv = (GridView) view.findViewById(R.id.election_gvCandidate);
//        candidateGv.setOnItemClickListener(this);
//        candidateGv.setNumColumns(2);

        candidateGv = (IRecyclerView) view.findViewById(R.id.election_gvCandidate);
        candidateGv.setLayoutManager(new GridLayoutManager(mContext, 2));
        candidateGv.addItemDecoration(new GridItemDecoration(2, 2));
        loadMoreFooterView = /*new LoadMoreFooterView(mContext)*/(LoadMoreFooterView) candidateGv.getLoadMoreFooterView();
        Candidate[] canArr = election.candidateList;
        referenceCanMap = new HashMap<>();
        if (election.getElectionType() == 2 && canArr != null) {
            //推选候选人流程忽略接口中的canList
            for (int i = 0; i < canArr.length; i++) {
                canArr[i].posIndex = -1;
                referenceCanMap.put(canArr[i].voterCertNumber, i);
            }
            canList = new ArrayList<>(Arrays.asList(canArr));
        } else {
            canList = new ArrayList<>();
        }
        candidateGv.setIAdapter(canAdapter = new SearchCandidateAdapter(mContext, canList));
        candidateGv.addOnItemTouchListener(new OnRecycleItemClickListener(candidateGv) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
                LogUtils.i("onItemClick vh AdapterPosition =" + vh.getAdapterPosition());
                if (election.getElectionType() == 2)
                    updateCanditaInfo(vh.getAdapterPosition() - 2);
                else if (election.getElectionType() == 1)
                    updateCandidateInfo(vh.getAdapterPosition() - 2);
            }
        });
        if (election.getElectionType() == 1) {
            positionGv.setVisibility(View.GONE);
            searchLL = (LinearLayout) view.findViewById(R.id.election_llSearch);
            searchLL.setVisibility(View.VISIBLE);
            searchEt = (EditText) findView(R.id.election_etFilter);
            searchEt.setImeActionLabel(mContext.getResources().getString(R.string.query), EditorInfo.IME_ACTION_DONE);
            searchEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_DONE) {
                        onSearch(v.getText().toString());
                    }
                    return false;
                }
            });
            candidateGv.setOnLoadMoreListener(this);
            candidateGv.setLoadMoreEnabled(true);

        }
        initPosDescView();
        voteBtn = (Button) findView(R.id.election_btnDone);
        voteBtn.setOnClickListener(this);

        if (mBundle.containsKey(JSONKeys.Voter.AlreadyVote)) {
            List<Candidate> tempList = mBundle.getParcelableArrayList(JSONKeys.Voter.AlreadyVote);
            LogUtils.i("mBundle.containsKey(JSONKeys.Voter.AlreadyVote)" + tempList.size());
            parseVoteList(tempList);
        }
//        if (app.getInfoList() != null) {
//            List<Candidate> tempList = app.getInfoList();
//            LogUtils.i("mBundle.containsKey(JSONKeys.Voter.ChooseList)" + tempList.size());
//            parseVoteList(tempList);
//        }
        if (mBundle.containsKey(JSONKeys.Voter.ChooseList)) {
            List<Candidate> tempList = mBundle.getParcelableArrayList(JSONKeys.Voter.ChooseList);
            LogUtils.i("mBundle.containsKey(JSONKeys.Voter.ChooseList)" + tempList.size());
            parseVoteList(tempList);
        }
    }


    private void initPosDescView() {
        descLL = (LinearLayout) findView(R.id.election_llDesc);
        allowNumTv = (TextView) findView(R.id.posDesc_tvAllowNum);
        selNumTv = (TextView) findView(R.id.posDesc_tvSelNum);
        leastNumTv = (TextView) findView(R.id.posDesc_tvLeastNum);
        //设成透明
        descLL.setBackgroundColor(getResources().getColor(R.color.black_alpha));
        descLL.setAlpha(0f);

    }

    private void parseVoteList(List<Candidate> infoList) {
        for (int i = 0; i < infoList.size(); i++) {
            Candidate info = infoList.get(i);
            info.posIndex = -1;
            LogUtils.i("readRecord " + info.toString());
            if (referencePosMap.containsKey(info.getPositionId())) {
                //把下标赋给当前Candidate
                updatePosInfo(referencePosMap.get(info.getPositionId()));
            }
            if (referenceCanMap.containsKey(info.voterCertNumber)) {
                updateCanditaInfo(referenceCanMap.get(info.voterCertNumber));
            } else {
                canList.add(info);
                referenceCanMap.put(info.voterCertNumber, canList.size() - 1);
                updateCanditaInfo(canList.size() - 1);
            }

        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (parent.getId() == R.id.election_gvPosition) {
            updatePosInfo(position);
            updatePosDesc(posList.get(position));

        }
    }


    private void updatePosInfo(final int position) {
        if (lastPosPosition != -1) {
            posList.get(lastPosPosition).iSelected = false;
        }
        if (position >= posList.size()) {
            Toast.makeText(mContext, "无效的列表项", Toast.LENGTH_SHORT).show();

        } else {
            posList.get(position).iSelected = true;
        }
        posAdapter.notifyDataSetChanged();
        lastPosPosition = position;
    }

    /**
     * 显示当前职位的描述（可选，已选，至少的人数）
     *
     * @param info
     */
    private void updatePosDesc(final Positions info) {
        allowNumTv.setText(info.choseableCount + "人");
        selNumTv.setText(info.selectedcount + "人");
        leastNumTv.setText(info.requireCount + "人");
        if (mSet == null)
            mSet = new AnimatorSet();
        if (mSet.isStarted() || mSet.isRunning()) {
            mSet.cancel();
        }
        ObjectAnimator showAnimator = ObjectAnimator.ofFloat(descLL, "alpha", 0.0f, 1.0f);
        showAnimator.setDuration(200);
        ObjectAnimator hideAnimator = ObjectAnimator.ofFloat(descLL, "alpha", 1.0f, 0.0f);
        hideAnimator.setDuration(200);
        hideAnimator.setStartDelay(2000);
        mSet.playTogether(showAnimator, hideAnimator);
        mSet.start();
    }

    /**
     * 职位选举 、候选人信息中职位名称的处理
     *
     * @param position
     */
    private void updateCanditaInfo(final int position) {
        if (lastPosPosition == -1) {
            LogUtils.w("未选中任何职位");
            //  if (election.getElectionType() == 2)
            Toast.makeText(mContext, "未选中任何职位", Toast.LENGTH_SHORT).show();
            return;
        }

        Positions posInfo = posList.get(lastPosPosition);
        Candidate canInfo = canList.get(position);
        if ("2".equals(posInfo.restriction) && "男".equals(canInfo.voterGender)) {
            new SVProgressHUD(mContext).showInfoWithStatus("性别不符合要求");
            return;
        }
        // 先修改原职位下标的已选人数
        if (canInfo.posIndex != -1)
            posList.get(canInfo.posIndex).selectedcount--;

        if (/*!posInfo.positionName.equals(canInfo.positionName)*/lastPosPosition != canInfo.posIndex) {
            //!posInfo.positionName.equals(canInfo.positionName在职位选举开始就有候选人列表使好使，候选人选举，职位列表为空，不好使
            //当前职位名称不等于候选人信息已有职位名称时，对候选人赋值
            canInfo.setPositionId(posInfo.positionId);
            canInfo.setPositionName(posInfo.positionName);
            canInfo.posIndex = lastPosPosition;
            posInfo.selectedcount++;

        } else {
            canInfo.setPositionId(0);
            canInfo.posIndex = -1;
            canInfo.setPositionName("");
        }
        canAdapter.notifyItemChanged(position);
        updatePosDesc(posInfo);
        //  lastPosPosition = -1;
    }

    /**
     * 提名候选人操作点击候选人
     *
     * @param position
     */
    private void updateCandidateInfo(final int position) {
        if (position > canList.size()) {
            return;
            //throw new IndexOutOfBoundsException("indexOutOfBound position =" + position + " , size = " + canList.size());
        }
        Candidate canInfo = canList.get(position);
        // 先修改原职位下标的已选人数
        Positions posInfo;

        if (canInfo.posIndex != -1) {
            //已被选择为某职位
            posInfo = posList.get(canInfo.posIndex);
            posInfo.selectedcount--;
            canInfo.setPositionId(0);
            canInfo.posIndex = -1;
            canInfo.setPositionName("");
        } else {
            //未被选择过的人员
            int firstPosition;  //优先判断女性人数是否满足
            int secPosition;
            int index;
            if ("2".equals(posList.get(0).restriction))
                firstPosition = 0;
            else
                firstPosition = 1;
            secPosition = firstPosition == 0 ? 1 : 0;
            Positions firposInfo = posList.get(firstPosition);
            Positions secposInfo = posList.get(secPosition);
            if ("女".equals(canInfo.voterGender) && (firposInfo.selectedcount < firposInfo.requireCount || (secposInfo.selectedcount >= secposInfo.requireCount && firposInfo.selectedcount < firposInfo.choseableCount))) {
                index = firstPosition;
            } else
                index = secPosition;
            posInfo = posList.get(index);
            canInfo.setPositionId(posInfo.positionId);
            canInfo.setPositionName(posInfo.positionName);
            canInfo.posIndex = index;
            posInfo.selectedcount++;


        }
        canAdapter.notifyItemChanged(position);
        updatePosDesc(posInfo);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.election_btnDone:
                if (checkParam()) {
                    vote();
                }
                break;
            case R.id.election_btnQuery:
//                if (TextUtils.isEmpty(searchEt.getText())) {
//                    Toast.makeText(mContext, "请输入过滤条件", Toast.LENGTH_SHORT).show();
//                } else {
                onSearch(searchEt.getText().toString());
//                }
                break;
            default:
                break;
        }
    }

    //检查投票人数是否满足要求
    private boolean checkParam() {
        for (Positions info : posList
                ) {
            if (info.selectedcount > info.choseableCount) {
                showPromptDialog(info.positionName + "最多可选" + info.choseableCount + "人,当前已选" + info.selectedcount + "人");
                // Toast.makeText(mContext, info.positionName + "最多可选" + info.choseableCount + "人,当前已选" + info.selectedcount + "人", Toast.LENGTH_LONG).show();
                return false;
            } else if (info.requireCount != 0 && info.selectedcount < info.requireCount) {
                // Toast.makeText(mContext, info.positionName + "至少选" + info.requireCount + "人,当前已选" + info.selectedcount + "人", Toast.LENGTH_LONG).show();
                showPromptDialog(info.positionName + "至少选" + info.requireCount + "人,当前已选" + info.selectedcount + "人");
                return false;

            }
        }
        return true;
    }

    private void vote() {
        //过滤出投票的数据
        new VoteTask().execute();
    }

    @Override
    public void onLoadMore(View view) {
        if (loadMoreFooterView.canLoadMore() && canAdapter.getItemCount() > 0) {
            loadMoreFooterView.setStatus(LoadMoreFooterView.Status.LOADING);
            if (hasMore /*&& !TextUtils.isEmpty(searchEt.getText())*/)
                new SearchTask().execute(searchEt.getText().toString());
            else {
                Toast.makeText(mContext, "当前没有更多加载项", Toast.LENGTH_SHORT).show();
                loadMoreFooterView.setStatus(LoadMoreFooterView.Status.THE_END);
            }
        }
//        else {
//            loadMoreFooterView.setStatus(LoadMoreFooterView.Status.THE_END);
//        }
    }

    private void onSearch(String str) {
//        if (!TextUtils.isEmpty(str)) {
        currentCount = 0; //重置可读取的数据量
        totalCount = 0;
        loadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
        filterFlag = true;
        new SearchTask().execute(str);
//        }
    }

    class VoteTask extends AsyncTask<String, Integer, Integer> {
        private ArrayList<Candidate> voteList;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            voteList = new ArrayList<>();
            for (int i = 0; i < canList.size(); i++) {
                if (!TextUtils.isEmpty(canList.get(i).getPositionName())) {
                    voteList.add(canList.get(i));
                }
            }
            if (voteList.size() == 0) {
                Toast.makeText(mContext, "空票", Toast.LENGTH_SHORT).show();
            }

            showProgressDialog("投票信息提交中...请稍后");
            voteBtn.setClickable(false);
        }

        @Override
        protected Integer doInBackground(String... params) {
            return mExampleClient.writeRecord(cardId, String.valueOf(election.electionId), voteList);
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            dismissDialog();
            voteBtn.setClickable(true);
            Toast.makeText(mContext, mExampleClient.getErrorMessage(integer), Toast.LENGTH_LONG).show();
            if (integer == ExampleClient.Success) {
                removeFragment();
            }
        }
    }

    class SearchTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            searchEt.setEnabled(false);
            queryBtn.setEnabled(false);
            if (totalCount == 0) {
                showProgressDialog("正在检索请稍后....");
            }
        }

        @Override
        protected String doInBackground(String... params) {
            return mExampleClient.searchVoter(election.regionId, params[0], QUERY_COUNT, currentCount);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
           // LogUtils.i("搜索结果" + s);
            loadMoreFooterView.setStatus(LoadMoreFooterView.Status.GONE);
            searchEt.setEnabled(true);
            queryBtn.setEnabled(true);
            if (totalCount == 0)
                dismissDialog();
            if (TextUtils.isEmpty(s)) {
                Toast.makeText(mContext, "检索超时", Toast.LENGTH_SHORT).show();
            } else {
                try {
                    JSONObject retJson = new JSONObject(s);
                    int retCode = CommonUtil.GetJsonIntValue(retJson, JSONKeys.Voter.ResultCode, -1);
                    if (retCode != 0) {
                        Toast.makeText(mContext, mExampleClient.getErrorMessage(retCode), Toast.LENGTH_SHORT).show();
                    } else {
                        parseSearchResult(retJson);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void parseSearchResult(JSONObject retJson) throws JSONException {
        JSONArray jsonArray = retJson.getJSONArray(JSONKeys.Voter.VoterList);

        totalCount = CommonUtil.GetJsonIntValue(retJson, JSONKeys.Voter.TotalCount, 0);
        if (totalCount < QUERY_COUNT) {
            loadMoreFooterView.setStatus(LoadMoreFooterView.Status.THE_END);
        }
        currentCount += jsonArray.length();
        hasMore = totalCount > currentCount;
        LogUtils.i("totalCount = " + totalCount + " , currentCount = " + currentCount);
        ArrayList<Candidate> filterList = new ArrayList<>();
        ArrayList<Integer> idList = new ArrayList<>();
        for (int i = 0; i < canList.size(); i++) {

            if (filterFlag) {
                if (0 != canList.get(i).getPositionId()) {
                    filterList.add(canList.get(i));
                    idList.add(canList.get(i).voterId);
                }
            } else {
                filterList.add(canList.get(i));
                idList.add(canList.get(i).voterId);
            }
        }
        filterFlag = false;
        canList.clear();
        canList.addAll(filterList);
        for (int i = 0; i < jsonArray.length(); i++) {
            Candidate info = mGson.fromJson(jsonArray.getJSONObject(i).toString(), Candidate.class);
         //   LogUtils.i(" info " + info.toString());

            //列表中不存在的项添加
            if (!idList.contains(info.voterId)) {
                info.posIndex = -1;
//                if (recordMap.containsKey(info.voterId)) {
//                    //搜索到了已被标记为其他职位的候选人
//                    int index = recordMap.get(info.voterId);
//                    if (index != -1 && index < recordList.size()) {
//                        info.setPositionId(recordList.get(index).getPositionId());
//                        info.setPositionName( recordList.get(index).getPositionName());
//                    }
//                }
                canList.add(info);

            }
        }
        canAdapter.notifyDataSetChanged();

    }
}
